//
//  SZCGiftViewController.m
//  礼物说
//
//  Created by dllo on 16/4/19.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "SZCGiftViewController.h"

/** title网址*/
#define kTITLEURL @"http://api.liwushuo.com/v2/channels/preset?gender=1&generation=1"
/**轮播的网址 */
#define KLUNBOURL @"http://api.liwushuo.com/v2/banners?channel=iOS"
/**中间滚动图 */
#define kZHUANTISURL @"http://api.liwushuo.com/v2/secondary_banners?gender=1&generation=2"
/** 大数据的网址*/
#define kBIGDATAURL [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?ad=2&gender=1&generation=2&limit=20&offset=%@",num, page]

@interface SZCGiftViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

/** title的点击collectionView*/
@property (nonatomic, retain) BaseCollectionView *titleCollection;
/** 轮播图collectionView*/
@property (nonatomic, retain) BaseCollectionView *buttomCollection;
/**用于通知 */
@property (nonatomic, retain) BaseCollectionView * refurbishCollectionView;
@property (nonatomic, retain) BaseCollectionView * loadCollectionView;

/** title的数组*/
@property (nonatomic, retain) NSMutableArray *titleModelArr;
/** 轮播数组*/
@property (nonatomic, retain) NSMutableArray *lunBoModelArr;
/**专题的数组 */
@property (nonatomic, retain) NSMutableArray *zhaunTiModelArr;
/** 点击的是哪个 row*/
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) NSInteger distance;
/**字典用来接收不同的页面作为key值，value接收数组*/
@property (nonatomic, retain) NSMutableDictionary * mDic;
/** 临时的数组*/
@property (nonatomic, retain) NSMutableArray *smallArr;
/**一个数据的数组 */
@property (nonatomic, retain) NSMutableArray * tempArr;
/**用于判断是否处于同一个页面下 */
@property (nonatomic, assign) NSInteger decide;

@property (nonatomic, retain) ButtonView *buttonView;


@end

@implementation SZCGiftViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"上拉加载" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"下拉刷新" object:nil];
    [_titleCollection release];
    [_buttomCollection release];
    [_titleModelArr release];
    [_lunBoModelArr release];
    [_zhaunTiModelArr release];
    [_mDic release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"嗨购";
    self.navigationController.navigationBar.translucent = NO;
    /** 防止内置*/
    self.automaticallyAdjustsScrollViewInsets = NO;
    //自动,防止过小导致的没有出现collectionView
    self.providesPresentationContextTransitionStyle = NO;
    // Do any additional setup after loading the view.
    
#pragma mark - BarButton(right)
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousu.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    [GiFHUD setGifWithImageName:@"HUD.gif"];
    
    /** 创建通知*/
    [self notifacationCenter];
    /** 创建title的collectionView*/
    [self createTitle];
    /** title数据请求*/
    [self dataHandle];
    /** 创建底层collectionView作为空白滑动*/
    [self createCollection];
    /** 创建下角标*/
    [self createButton];
    
#pragma mark - 数据请求的关键变量
    /** 临时数组*/
    self.smallArr = [NSMutableArray array];
    /** 接受临时数组的数组*/
    self.tempArr = [NSMutableArray array];
    /** 判断是哪一个页面的，用于是接受临时数组还是覆盖临时数组*/
    self.decide = 0;
    /** 一个大字典，用于接受不同的title页面，把页面作为key值，value储存tempArr数组*/
    self.mDic = [NSMutableDictionary dictionary];
    
}

#pragma mark - （right）BarButton 点击方法
- (void)rightButtonAction{
    SearchViewController * seachVc = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:seachVc animated:YES];
    [seachVc release];
}

#pragma mark - 下拉刷新，上拉加载
/** 创建通知*/
- (void)notifacationCenter {
    /** 通知的接收者（下拉刷新）*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refurbisAction:) name:@"下拉刷新" object:nil];
    /** 通知的接收值（上拉加载）*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadAction:) name:@"上拉加载" object:nil];
}
/** 下拉刷新，通知响应*/
- (void)refurbisAction:(NSNotification *)sender {
    self.refurbishCollectionView = sender.userInfo[@"collectionview"];
    NSInteger number = [sender.userInfo[@"index"] integerValue];
    [self bigDataHandlePage:@"0" Index:number];
}
/** 上拉加载，通知响应*/
- (void)loadAction:(NSNotification *)sender {
    self.loadCollectionView = sender.userInfo[@"collectionview"];
    NSInteger number = [sender.userInfo[@"index"] integerValue];
    [self bigDataHandlePage:sender.userInfo[@"num"] Index:number];
}


#pragma mark - 数据处理
#pragma mark - title数据解析
- (void)dataHandle {
    [XRAFNetworkTool GETUrl:kTITLEURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray *data = responseObject[@"data"][@"channels"];
        /** model 赋值被封装*/
        self.titleModelArr = [TitleModel modelHandleWithArray:data];
        [_titleCollection reloadData];
        /** 在请求轮播*/
        [self dataLunBoHandle];
        [self createView];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"Title%@", error);
        [GiFHUD dismiss];
    }];
}

#pragma mark - 轮播图数据解析
- (void)dataLunBoHandle {
    [XRAFNetworkTool GETUrl:KLUNBOURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray *data = responseObject[@"data"][@"banners"];
        self.lunBoModelArr = [LunBoModel modelHandleWithArray:data];
//        [_buttomCollection reloadData];
        /** 专题*/
        [self zhuanTiData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"轮播%@", error);
    }];
}

#pragma mark - 专题数据解析
- (void)zhuanTiData {
    [XRAFNetworkTool GETUrl:kZHUANTISURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray *data = responseObject[@"data"][@"secondary_banners"];
        self.zhaunTiModelArr = [ZhuanTiModels modelHandleWithArray:data];
        
        [self bigDataHandlePage:@"0" Index:0];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"专题%@", error);
    }];
}

#pragma mark - 内容数据解析
- (void)bigDataHandlePage:(NSString *)page Index:(NSInteger)index {
    /** 从上一个titleModel 中取出我们要的id*/
    if (_titleModelArr.count != 0) {
        TitleModel *model = _titleModelArr[index];
        /** 将model中的num的NSNumber类型转换为NSString*/
        NSNumber *num = model.number;
        
        /** 内容数据请求*/
        [XRAFNetworkTool GETUrl:kBIGDATAURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
            /** 将数据请求出的字典 取出我想要的数组*/
            NSArray *data = responseObject[@"data"][@"items"];
            /**一个临时的数组，装model赋值后的数据*/
            /**目的是为后面的判断，如果页面相同，而page不同，则将smallArr数组add到tempArr的后面，原来temp数组中的数组还在，只是添加元素。
             如果页面不同，将smallArr数组直接去覆盖tempArr数组，这样数组就是新的
             此方法用于判断上拉加载，下拉刷新*/
            self.smallArr = [ContentModel modelHandleWithArray:data];
            NSLog(@"555555555555%@", self.smallArr);
            /**判断是如果页面相同，此方法为的是上拉加载，下拉刷新 */
            if (_decide == index) {
                /**判断不同页面的page，网址中的页数是第一页，则是下拉刷新*/
                if ([page isEqualToString:@"0"]) {
                    /**删除如有数据 */
                    [self.tempArr removeAllObjects];
                }
                /** 如果是同一个页面，不同的page则添加数组*/
                [self.tempArr addObjectsFromArray:_smallArr];
            }else {
                /** 如果不同刷新数组*/
                self.tempArr = _smallArr;
                /** 将当页面赋给下一个页面*/
                _decide = index;
            }
            /** 分类不同页面的数据*/
            [self.mDic setObject:_tempArr forKey:[NSString stringWithFormat:@"%ld", (long)index]];
            /** 记得reloadData*/
            if (_tempArr > 0) {
                [_buttomCollection reloadData];
            }
            [GiFHUD dismiss];
            /** 如果成功，我们就关闭上拉加载下拉刷新*/
            [_refurbishCollectionView.mj_header endRefreshing];
            [_loadCollectionView.mj_footer endRefreshing];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"55555555%@", error);
            [GiFHUD dismiss];
        }];
    }
}

#pragma mark - 创建title的collectionView
- (void)createTitle {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 10;
    layout.itemSize = CGSizeMake(kWIDTHS(80), kHEIGHTS(30));
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.titleCollection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, kWIDTHS(335), kHEIGHTS(30)) collectionViewLayout:layout];
    _titleCollection.pagingEnabled = NO;
//    _titleCollection.backgroundColor = [UIColor whiteColor];
    _titleCollection.delegate = self;
    _titleCollection.dataSource = self;
    [self.view addSubview:_titleCollection];
    [_titleCollection release];
    [layout release];
    [self.titleCollection registerClass:[TitleCollectionViewCell class] forCellWithReuseIdentifier:@"titleCell"];
 
    /** 默认第一个row*/
    self.index = 0;
    self.distance = 0;
}

/** View*/
- (void)createView {
    self.buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(0, 0, kWIDTHS(375), kHEIGHTS(667) - 49)];
    self.buttonView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_buttonView];
    _buttonView.hidden = YES;
    _buttonView.modelArr = _titleModelArr;
    [_buttonView release];
    
    /** block传值*/
    _buttonView.block = ^void(NSInteger index) {
        /**获取上一个bottomCollectionView的偏移量*/
        CGFloat offent = _buttomCollection.contentOffset.x;
        /**获取上一个点击时的tag值 */
        NSInteger tag = offent / kWIDTH + 1000;
        /**获取上一个label */
        UILabel * beforeLabel = [self.view viewWithTag:tag];
        /**还原上一个label的字体颜色和背景颜色 */
        beforeLabel.textColor = [UIColor grayColor];
        
        /**找到当前label的并改变字体颜色和label的背景颜色 */
        UILabel *label = [self.view viewWithTag:1000 + index];
//                label.backgroundColor = UIColorFromRGB(0x20B2AA);
        label.textColor = UIColorFromRGB(0XFF2841);
        _buttomCollection.contentOffset = CGPointMake(index * kWIDTH, 0);
        
        self.index = index;
        
        if (index > 3 &&  index < _titleModelArr.count -
            2) {
            
            _titleCollection.contentOffset = CGPointMake(kWIDTHS(65) * (index - 3), 0);
        }else if(index == 0){
            
            _titleCollection.contentOffset = CGPointMake(0, 0);
        }else if(index == _titleModelArr.count - 1){
            
            _titleCollection.contentOffset = CGPointMake(kWIDTHS(65) * (index - 5), 0);
        }
#pragma 点击哪一个对哪一个进行网络请求
        /**判断是点击后的数组中有没有值，如果没有值，则进行网络请求 */
        NSArray * array = _mDic[[NSString stringWithFormat:@"%ld", index]];
        if ( array.count == 0) {
            [GiFHUD show];
            [self bigDataHandlePage:@"0" Index:index];
            NSLog(@"%ld",_titleModelArr.count);
        }
        self.buttonView.hidden = YES;
    };
}

#pragma mark - 创建下角标
- (void)createButton {
    
    /** 下角标*/
    BaseButton *button = [BaseButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(kWIDTHS(335), 0, kWIDTHS(40), kHEIGHTS(30));
    [button setImage:[[UIImage imageNamed:@"xiasanjiao.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
}

- (void)buttonAction {
    _buttonView.hidden = NO;
}


#pragma mark - 创建底层滑动的collectionView
- (void)createCollection {
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
#warning 注意：我们在自定义cell的宽度的时候，要注意不要使用比例给适配，给一个固定的值，屏幕宽度，否则会有小数点的误差，到时偏移量不精确，有小数点，使用tag的时候会发生错误
    layout.itemSize = CGSizeMake(kWIDTH, kHEIGHTS(665) - 49 - 64 - kWIDTHS(30));
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.buttomCollection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, kWIDTHS(30), kWIDTH, kHEIGHTS(667) - kHEIGHTS(30) - 49 - 64) collectionViewLayout:layout];
    self.buttomCollection.pagingEnabled = YES;
    _buttomCollection.contentOffset = CGPointMake(0, 0);
    
    [self.view addSubview:_buttomCollection];
    [_buttomCollection release];
    [layout release];
    
    /**开启回弹的效果为的是实现scrollview的减速结束的一个title字体变红的效果，因为在第一章和最后一张如果没有回弹效果就会没有 */
    _buttomCollection.bounces = YES;
    
    _buttomCollection.delegate = self;
    _buttomCollection.dataSource = self;
    
    [_buttomCollection registerClass:[ButtomCollectionViewCell class] forCellWithReuseIdentifier:@"buttomCell"];
    
    [_buttomCollection registerClass:[OtherCollectionViewCell class] forCellWithReuseIdentifier:@"otherCell"];
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return _titleModelArr.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _titleCollection) {
        
        TitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"titleCell" forIndexPath:indexPath];
        cell.model = _titleModelArr[indexPath.row];
        cell.titleLable.tag = 1000 + indexPath.row;
        cell.titleLable.textColor = [UIColor grayColor];
//        cell.backgroundColor = [UIColor yellowColor];
        if (_index == indexPath.row) {
            cell.titleLable.textColor = UIColorFromRGB(0XFF2841);
        }
        return cell;
        
    }else {
        if (indexPath.row == 0) {
            /** 精选*/
            ButtomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"buttomCell" forIndexPath:indexPath];
        /**传输带有model的轮播数组 */
            cell.lunBoArr = _lunBoModelArr;
            cell.index = indexPath.row;
            NSLog(@"%@", _lunBoModelArr);
        /**传输带有精选数据的数组 */
            cell.jingXuanArr = _mDic[[NSString stringWithFormat:@"%ld", indexPath.row]];
            cell.zhuanTiModelArr = _zhaunTiModelArr;
            [cell.collectionView reloadData];
            return cell;
            
        }else {
            OtherCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"otherCell" forIndexPath:indexPath];
            /**传递精选外的数组 */
            cell.index = indexPath.row;
            cell.haiTaoArr = _mDic[[NSString stringWithFormat:@"%ld", indexPath.row]];
            [cell.collectionView reloadData];
            return cell;
        }
    }
}

/** Cell 的大小*/
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView != _titleCollection) {
        return CGSizeMake(kWIDTH, kHEIGHTS(667) - 64 - 49 - kWIDTHS(30));
    }else{
        return CGSizeMake(kWIDTHS(60), kWIDTHS(30));
    }
}


#pragma mark - 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == _titleCollection) {
        /**获取上一个bottomCollectionView的偏移量*/
        CGFloat offent = _buttomCollection.contentOffset.x;
        /**获取上一个点击时的tag值 */
        NSInteger tag = offent / kWIDTH + 1000;
        /**获取上一个label */
        UILabel * beforeLabel = [self.view viewWithTag:tag];
        /**还原上一个label的字体颜色和背景颜色 */
        beforeLabel.textColor = [UIColor grayColor];
        /**找到当前label的并改变字体颜色和label的背景颜色 */
        UILabel *label = [self.view viewWithTag:1000 + indexPath.row];
        label.textColor = UIColorFromRGB(0XFF2841);
        /**迁移量 */
        _buttomCollection.contentOffset = CGPointMake(indexPath.row * kWIDTH, 0);
        
        self.index = indexPath.row;
        NSLog(@"%d",(int)_buttomCollection.contentOffset.x);
        
#pragma mark - 点击移到中间
        if (indexPath.row > 2  &&  indexPath.row < _titleModelArr.count - 2)
        {
            collectionView.contentOffset = CGPointMake(kWIDTHS(62) * indexPath.row - kWIDTHS(180), 0);
        }
        
        //#pragma 点击哪一个对哪一个进行网络请求
        /**判断是点击后的数组中有没有值，如果没有值，则进行网络请求 */
        NSArray * array = _mDic[[NSString stringWithFormat:@"%ld", indexPath.row]];
        if ( array.count == 0) {
            [GiFHUD show];
            [self bigDataHandlePage:@"0" Index:indexPath.row];
            NSLog(@"%ld",_titleModelArr.count);
        }
    }
}

/**可以检测开始拖拽之前的偏移    将要开始拖拽的时候*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _buttomCollection) {
        
        /**获取没有拖拽前的偏移量 */
        CGFloat offent =_buttomCollection.contentOffset.x;
        /**获取没有拖拽前的tag */
        NSInteger tag = offent / kWIDTH + 1000;
        /**获取没有拖拽前的label */
        UILabel *label = [self.view viewWithTag:tag];
        /**还原颜色*/
        label.textColor = [UIColor grayColor];
    }
}

/**可以检测减速之后的偏移 ----    减速已经结束的是时候 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView == _buttomCollection) {
        
        
        /**获取拖拽后的偏移量 */
        CGFloat offent = _buttomCollection.contentOffset.x;
        /**获取拖拽后的tag */
        NSInteger index = offent / kWIDTH;
        _index = index;
        NSInteger tag = offent / kWIDTH + 1000;
        NSLog(@"迁移量：%lf", offent);
        NSLog(@"屏幕宽：%lf", kWIDTH);
        /**获取拖拽后的label */
        UILabel *label = [self.view viewWithTag:tag];
        /**改变颜色 */
        label.textColor = UIColorFromRGB(0XFF2841);
        
        /**当改变到第4个的时候，滑动titleCollectionView 到倒数第三个cell结束 */
        if (offent > kWIDTH * 2 && offent < kWIDTH * (self.titleModelArr.count - 3)) {
            int i = offent / kWIDTH - 3;
#warning 警告： 我给了一个固定的偏移数： 70，应该计算，偏移的数，
            _titleCollection.contentOffset = CGPointMake(kWIDTHS(72) * i, 0);
        }
#pragma 滑动到哪一个页面对哪一个页面进行网络请求
        /**滑动控制哪一个页面去请求 */
        /**计算滑动到哪一页 */
        NSInteger page = offent / kWIDTH;
        
        /**取出要滑动页的数组，如果数组中有值则不进行网络请求 */
        NSArray * array = _mDic[[NSString stringWithFormat:@"%ld", page]];
        if ( array.count == 0) {
            [GiFHUD show];
            [self bigDataHandlePage:@"0" Index: page];
            NSLog(@"%ld",_titleModelArr.count);
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"请求");
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
